//
//  STMobileCommodityController.swift
//  iPhone
//
//  Created by Toj on 8/9/22.
//

import UIKit

class STMobileCommodityController: STBaseCommodityController {

    public let viewModel = STCommodityMobileViewModel()
    
    public weak var allViewModel: STCommodityAllViewModel? { didSet {
        allViewModel?.mobileProductRequest = { [weak self] product in
            // 检查 返回的商品是不是优惠券商品
            let isCouponProduct = self?.couponProductFollowUp(product)
            // 是优惠券商品展示优惠券商品
            if isCouponProduct == true,
                let couponProduct = self?.viewModel.selectedProduct {
                self?.productDetailRequest(product: couponProduct)
                return
            }
            self?.productDetailRequest(product: product)
        }
        
        allViewModel?.didTapProductHandle = { [weak self] product in
            self?.didTapProductCallBack(product)
        }
    } }
    
    // 点击All商品
    private func didTapProductCallBack(_ product: MemberProductDto) {
        // 当前展示商品 与点击商品一致 &&
        // 有数据展示 不刷新商品 &&
        // 不是根据某个优惠券进来的
        if product.id == viewModel.currentProduct?.id &&
            notDataView.isHidden &&
            couponId == 0 { return }
        couponId = 0
        couponInstanceID = ""
        buyNowView.isShowCoupon = false
        productDetailRequest(product: product)
    }
    
    private func couponProductFollowUp(_ product: MemberProductDto) -> Bool {
        guard couponId > 0 else { return false }
        guard let productID = viewModel.selectedProduct?.id else {
            couponId = 0
            couponInstanceID = ""
            return false
        }
        // 不是优惠券对应的商品id清空优惠券参数信息
        if productID == product.id { return true }
        couponId = 0
        couponInstanceID = ""
        return false
    }
    
    // 内部根据这些参数具体请求那个接口, 如果([cpi/cps]==is)失败必须清空否则还会请求is接口
    public var utmString = ""
    public var channelID = 0
    public var vodID = 0
    public var productId = 0
    // 查询优惠券优惠信息
    public var couponInstanceID = ""
    // 查询优惠券对应的商品
    public var couponId = 0 { didSet {
        viewModel.isFromCoupons = couponId > 0
        print("-->toj: isFromCoupons: \(viewModel.isFromCoupons)")
    } }
    public var selectedProduct: MemberProductDto? = nil { didSet {
        guard let product = selectedProduct else { return }
        viewModel.selectedProduct = product
    } }
    
    private var sectionModels: [STCommodityMobileSectionModel] = [] { didSet {
        notDataView.isHidden = !sectionModels.isEmpty
        collectionView.reloadData()
        guard !notDataView.isHidden else { return }
        buyNowView.isHidden = true
        setupMakeLayoutNotDataView()
    } }
    
    private lazy var buyNowView: BuyNowFloatingView = {
        let view = BuyNowFloatingView()
        view.backgroundColor = UIColor.white.st_alpha(0.96)
        view.delegate = self
        view.isHidden = true
        view.st_shadow()
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupCollectionView()
        setupMakeAddSubviews()
        setupMakeAddObserver()
        
        commodityDetailRequest()
        
        bottomOffset = buyButtonHeight
    }
    
    private func setupMakeAddSubviews() {
        view.addSubview(buyNowView)
        
        buyNowView.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(buyButtonHeight)
        }
    }
    
    override func registerCollectionViews() {
        super.registerCollectionViews()
        // 商品详情
        collectionView.register(MBCommodityDetailCell.cell_class, forCellWithReuseIdentifier: MBCommodityDetailCell.cell_identifier)
        // 商品捆绑包
        collectionView.register(MBCommodityBundledCell.cell_class, forCellWithReuseIdentifier: MBCommodityBundledCell.cell_identifier)
        // 固定有效期包
        collectionView.register(MBCommodityEffectiveCell.cell_class, forCellWithReuseIdentifier: MBCommodityEffectiveCell.cell_identifier)
        
        // 规格说明
        collectionView.register(MBCommodityDetailTipsCell.cell_class, forCellWithReuseIdentifier: MBCommodityDetailTipsCell.cell_identifier)
        
        // 支付渠道 header
        collectionView.register(STChannelHeaderView.cell_class, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: STChannelHeaderView.cell_identifier)
        // 支付渠道
        collectionView.register(STChannelCell.cell_class, forCellWithReuseIdentifier: STChannelCell.cell_identifier)
        // 支付渠道 - 银行卡
        collectionView.register(STChannelCardCell.cell_class, forCellWithReuseIdentifier: STChannelCardCell.cell_identifier)
        // 支付渠道 footer
        collectionView.register(STChannelFooterView.cell_class, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: STChannelFooterView.cell_identifier)
        
        // 权益
        collectionView.register(MBCommodityRightsCell.cell_class, forCellWithReuseIdentifier: MBCommodityRightsCell.cell_identifier)
        // 推荐商品
        collectionView.register(MBCommodityRecommendCell.cell_class, forCellWithReuseIdentifier: MBCommodityRecommendCell.cell_identifier)
        
        // 服务协议
        collectionView.register(MBCommodityServiceCell.cell_class, forCellWithReuseIdentifier: MBCommodityServiceCell.cell_identifier)
    }
    
    private func setupMakeAddObserver() {
        
    }
    
    private let buyButtonHeight: CGFloat = 96.ui_scale
    
    private func setupCollectionView() {
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
    internal override func reloadHeaderInfo() {
        headerView?.setMembershipInfo(segmentType: type, product: viewModel.currentProduct)
        showCouponAlert()
    }
    
    internal override func reloadInfo() {
        reloadBuyNowInfo()
        reloadHeaderInfo()
        viewModel.ds_buyDataStatistics(action: "buy_show")
    }

    internal override func changedWalletAmount() {
        viewModel.changedWalletAmount()
        
        guard let commodityChannel = viewModel.channelsSection?.commodityChannel else {
            return
        }
        collectionView.reloadData()
        guard commodityChannel.selectedChannel?.isEWallet == true else { return }
        reloadBuyNowInfo()
    }
    
    private var couponAlertView: MBCouponAlert?
    private func showCouponAlert() {
        guard let headerSuperView = headerView?.superview,
        headerSuperView == collectionView && !view.isHidden, !buyNowView.isHidden else { return }
        // 当天没显示
        guard !TimeCacheManager.manager.todayCache(type: .couponAlert)
        else { return }
        
        // 有优惠券
        // 重新选择商品后会清空这个值
        let isShowCoupon = buyNowView.isShowCoupon
        guard isShowCoupon else { return }
        // 规格有效
        guard let commodity = buyNowView.model else { return }
        // 当天状态
        TimeCacheManager.manager.setTodayCache(type: .couponAlert)
        
        let couponAlert = MBCouponAlert()
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let window = appDelegate.window else { return }
        
        let toPosition = window.convert(buyNowView.actualPriceLabel.center, from: buyNowView)
        print("-->toj: toPosition: \(toPosition)")
        couponAlert.toPosition = toPosition
        couponAlert.model = commodity
        couponAlert.delegate = self
        
        view.superview?.addSubview(couponAlert)
        couponAlert.frame = view.bounds
        couponAlert.animationCoupon()
        couponAlertView = couponAlert
    }
    
    private func reloadBuyNowInfo() {
        buyNowView.needShowCoupon = !viewModel.isFromCoupons
        buyNowView.model = viewModel.selectedCommodity
        buyNowView.productModel = viewModel.currentProduct
        buyNowView.currentChannel = viewModel.channelsSection?.commodityChannel?.selectedChannel
        showCouponAlert()
    }
    
    deinit {
        print("-->toj: STMobileCommodityController: deinit")
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - 数据请求
extension STMobileCommodityController {
    
    public func commodityDetailRequest() {
        
        // 联盟商品
        if !utmString.isEmpty {
            unionProductRequest()
            return
        }

        // 从直播视频进入
        if channelID > 0 {
            channelProductRequest()
            return
        }

        // 从点播视频进入
        if vodID > 0 {
            vodProductRequest()
            return
        }

        // 从优惠券进入
        if couponId > 0 {
            couponProductRequest()
            return
        }

        // 没有参数进商品列表,或者进商品详情
        allProductsRequest()
    }
    
    // 联盟商品
    private func unionProductRequest() {
        view.hud.show()
        print("-->toj: 联盟商品 utmString:\(utmString) productId: \(productId)")
        allViewModel?.requestProductOfUTM(utm: utmString, product: "\(productId)", { [weak self] isSuccess, product in
            
            self?.view.hud.hide()
            guard let weakself = self else { return }

            weakself.commodityDelegate?.commodityController(weakself, utmProductLoaded: isSuccess)
            
            // 走闭包
            // self?.reloadInfo()
            // self?.sectionModels = sectionModels
        })
    }
    
    // 从点播视频进入
    private func channelProductRequest() {
        view.hud.show()
        viewModel.requestProductOfChannel(id: channelID) { [weak self] in
            self?.view.hud.hide()
            self?.allProductsRequest()
        }
    }
    
    // 从点播视频进入
    private func vodProductRequest() {
        view.hud.show()
        viewModel.requestProductOfVod(id: vodID) { [weak self] in
            self?.view.hud.hide()
            self?.allProductsRequest()
        }
    }
    
    // 从优惠券进入
    private func couponProductRequest() {
        view.hud.show()
        viewModel.requestProductOfCoupon(id: couponId) { [weak self] in
            self?.view.hud.hide()
            self?.allProductsRequest()
        }
    }
    
    // 没有参数进商品列表,或者进商品详情
    private func allProductsRequest() {
        view.hud.enabled(false).show()
        
        var pid = viewModel.selectedProduct?.id ?? 0
        //print("-->toj: pid1: \(pid)")
        if productId > 0 { pid = productId }
        //print("-->toj: pid: \(pid), productId:\(productId)")
        
        allViewModel?.requestAllCommodityDetail(product: String(pid), { [weak self] isSuccess, product in
            self?.view.hud.hide()
            // 走闭包
            if !isSuccess {
                self?.sectionModels = []
                return
            }
//            guard let currentProduct = product else { return }
//            self?.productDetailRequest(product: currentProduct)
        })
    }
    
    // 更新某个商品详情
    private func productDetailRequest(product: MemberProductDto, isShowHUD: Bool = true) {
        // 替换缓存
        selectedProduct = product
        guard product.id > 0 else {
            sectionModels = []
            return
        }
        print("-->toj: productId:\(product.id)")
        if isShowHUD { view.hud.show() }
        viewModel.dataBundleInfo = allViewModel?.dataBundleInfo
        viewModel.requestMobileCommodityDetail(product: product, couponInstanceID: couponInstanceID, utm: utmString) { [weak self] isSuccess, sectionModels in
            
            if isShowHUD { self?.view.hud.hide() }
            if !isSuccess {
                self?.sectionModels = []
                return
            }
            
            self?.reloadInfo()
            self?.sectionModels = sectionModels
        }
    }
}

// MARK: - Private
extension STMobileCommodityController {
    
    private func didTapBuyPay() {
        if !STUserModel.shared.isRealUser() {
            UIHelper.showAlert(title: OLLocalize("notice_", comment: ""), message: OLLocalize("alert_login"), defaultTitle: OLLocalize("confirm_", comment: ""), cancelTitle: OLLocalize("cancel_", comment: ""), in: nil, defaultAction: {
                STSRouter.openLocalPage(RouterPage.login)
            })
            return
        }
        
        guard let commodity = viewModel.selectedCommodity,
        let channel = viewModel.channelsSection?.commodityChannel?.selectedChannel else { return }
        gotoBuyPay(commodity: commodity, channel: channel)
    }
    
    private func gotoBuyPay(commodity: MemberCommodityDto, channel: STChannelCellModel) {
        viewModel.ds_buyDataStatistics(action: "ProdBuy")
        STOrderPayManager.manager.orderBuy(commodity: commodity) { [weak self] order, state in
            // 下单失败
            if state.isFailed {
                self?.gotoBuyPayFailed(state: state)
                return
            }
            
            // 下单成功后
            guard let orderInfo = order else { return }
            // 价钱为0直接退出了不需要支付
            if state == .successPay { return }
            // 刷新当前商品优惠信息(主要是优惠券)
            if let product = self?.viewModel.currentProduct {
                let pid = String(product.id)
                let aProduct = self?.allViewModel?.products[pid] ?? product
                // 延迟0.25 等待页面动画结束后更新
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
                    self?.productDetailRequest(product: aProduct, isShowHUD: false)
                }
            }
            // 支付
            self?.viewModel.ds_orderPay(commodity: commodity)
            STOrderPayManager.manager.orderPay(channel: channel, order: orderInfo) { order, state in
                
            }
        }
    }
    
    private func gotoBuyPayFailed(state: STOrderBuyState) {
        // 价格计划改动需要刷新所有
        if state == .failedCode5 {
            commodityDetailRequest()
            return
        }
        // 刷新当前商品
        guard let product = viewModel.currentProduct else { return }
        productDetailRequest(product: product, isShowHUD: true)
    }
}

// MARK: - 代理事件 UICollectionViewDataSource
extension STMobileCommodityController: UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return sectionModels.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let sectionModel = sectionModels[section]
        
        // 规格
        if sectionModel.type.isCommodity == true {
            if  sectionModel.type == .commodityDataSave {
                return 1
            }
            
            return sectionModel.productViewModel?.commoditys.count ?? 0
        }
        
        // 提示
        // 服务协议
        if sectionModel.type == .commodityTips ||
           sectionModel.type == .serviceAgreement {
            return 1
        }
        
        // 支付渠道
        if sectionModel.type == .payChannel {
            return sectionModel.commodityChannel?.showNumber ?? 0
        }
        
        // 权益
        if sectionModel.type == .rights {
            return sectionModel.rights?.count ?? 0
        }
        
        // 推荐商品
        return sectionModel.products?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let sectionModel = sectionModels[indexPath.section]
        // 规格
        if sectionModel.type.isCommodity == true {
            // 会员包固定有效期
            if sectionModel.type == .commodityDataSaveLetValid {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MBCommodityEffectiveCell.cell_identifier, for: indexPath, MBCommodityEffectiveCell.self)
                cell.model = sectionModel.productViewModel?.commoditys[indexPath.row]
                cell.delegate = self
                return cell
            }
            
            // 会员包
            if sectionModel.type == .commodityDataSave {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MBCommodityDetailCell.cell_identifier, for: indexPath, MBCommodityDetailCell.self)
                cell.viewModel = sectionModel.productViewModel
                cell.delegate = self
                return cell
            }
            
            // 捆绑包
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MBCommodityBundledCell.cell_identifier, for: indexPath, MBCommodityBundledCell.self)
            cell.model = sectionModel.productViewModel?.commoditys[indexPath.row]
            cell.delegate = self
            return cell
        }
        
        // 规格说明
        if sectionModel.type == .commodityTips {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MBCommodityDetailTipsCell.cell_identifier, for: indexPath, MBCommodityDetailTipsCell.self)
            cell.model = sectionModel.commodityTips
            return cell
        }
        
        // 支付渠道
        if sectionModel.type == .payChannel {
            let channel = sectionModel.commodityChannel?.showChannels[indexPath.row]
            if channel?.isCarCell == true {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: STChannelCardCell.cell_identifier, for: indexPath, STChannelCardCell.self)
                cell.delegate = self
                cell.model = channel
                return cell
            }
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: STChannelCell.cell_identifier, for: indexPath, STChannelCell.self)
            cell.model = channel
            cell.delegate = self
            return cell
        }
        
        // 权益
        if sectionModel.type == .rights {
            let right = sectionModel.rights?[indexPath.row]
           
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MBCommodityRightsCell.cell_identifier, for: indexPath, MBCommodityRightsCell.self)
            cell.memberRight = right
            cell.delegate = self
            return cell
        }
        
        // 服务协议
        if sectionModel.type == .serviceAgreement {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MBCommodityServiceCell.cell_identifier, for: indexPath, MBCommodityServiceCell.self)
            return cell
        }
        
        let recommend = sectionModel.products?[indexPath.row]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MBCommodityRecommendCell.cell_identifier, for: indexPath, MBCommodityRecommendCell.self)
        cell.delegate = self
        cell.recommendProduct = recommend
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let sectionModel = sectionModels[indexPath.section]
        if kind == UICollectionView.elementKindSectionHeader {
            if sectionModel.type == .payChannel {
                // 为了定位支付渠道 在那个分区, 点击footer后滚动到上面
                sectionModel.commodityChannel?.sectionIndex = indexPath.section
                let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: STChannelHeaderView.cell_identifier, for: indexPath) as? STChannelHeaderView
                view?.section = sectionModel
                return view!
            }
            
            let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CommodityTitleView.cell_identifier, for: indexPath) as? CommodityTitleView
            view?.backgroundColor = .white
            view?.section = sectionModel
            return view!
        }
        
        if sectionModel.type == .payChannel {
            let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: STChannelFooterView.cell_identifier, for: indexPath) as? STChannelFooterView
            view?.mobileViewModel = sectionModel.commodityChannel
            view?.delegate = self
            return view!
        }

        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: UICollectionReusableView.cell_identifier, for: indexPath)
        view.backgroundColor = "#EEEEEE".to_color
        return view
    }
}

// MARK: - 代理事件 UICollectionViewDelegateFlowLayout
extension STMobileCommodityController: UICollectionViewDelegateFlowLayout {
    
    // section 上下左右的间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        
        let sectionModel = sectionModels[section]
        return sectionModel.layoutEdgeinset
    }
    
    // cell 大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let sectionModel = sectionModels[indexPath.section]
        return sectionModel.cellSize
    }
    
    // section header 大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        let sectionModel = sectionModels[section]
        return sectionModel.headerSize
    }
    
    // section footer 大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        
        let sectionModel = sectionModels[section]
        if section == collectionView.numberOfSections-1 {
            return STDefaultCellSize
        }
        return sectionModel.footerSize
    }
    
    // cell之间 垂直间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        let sectionModel = sectionModels[section]
        return sectionModel.minimumLineSpacing
    }

    // cell之间 水平间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        let sectionModel = sectionModels[section]
        return sectionModel.minimumInteritemSpacing
    }
}

// MARK: - 代理事件 MBCommodityRightsCellDelegate
extension STMobileCommodityController: MBCommodityBundledCellDelegate {
    
    func commodityBundledCellDidSelected(_ view: MBCommodityBundledCell) {
        guard let model = view.model,
              let product = viewModel.currentProduct
        else { return }
        
        DataStatistics.sendEvent(event: DSEvent(category: "CommodityBundledCell", action: "promo_click", label: model.name, value: "1", lt: .event))
        
        
        let alertView = MBCommodityPreferentialAlert()
        alertView.productModel = product
        alertView.model = model
        alertView.show(in: self.view)
        
        viewModel.selectedCommodity = model
        collectionView.reloadData()
        reloadBuyNowInfo()
//        buyNowView.needShowCoupon = !viewModel.isFromCoupons
//        buyNowView.model = model
//        buyNowView.productModel = viewModel.currentProduct
//        buyNowView.currentChannel = viewModel.channelsSection?.commodityChannel?.selectedChannel
        reloadBuyNowInfo()
        viewModel.ds_didTapCommodity(commodity: model)
    }
}

// MARK: - 代理事件 MBCommodityRightsCellDelegate
extension STMobileCommodityController: MBCommodityRightsCellDelegate {
    
    func commodityRightsCellDidTapRights(_ view: MBCommodityRightsCell) {
        guard let model = view.memberRight else { return }
        
        let event = DSEvent(category: st_className, action: "right_click", label: model.name, value: "1")
        DataStatistics.sendEvent(event: event)
        
        let vc = CommodityRightAlert()
        vc.model = model
        vc.channelArr   = viewModel.currentProduct?.channel_list ?? []
        vc.program_list = viewModel.currentProduct?.program_list ?? []
        vc.modalPresentationStyle = .custom
        present(vc, animated: true, completion: nil)
    }
}

// MARK: - 代理事件 MBCommodityRecommendCellDelegate
extension STMobileCommodityController: MBCommodityRecommendCellDelegate {
    
    func commodityRecommendCellDidTapRecommend(_ view: MBCommodityRecommendCell) {
        guard let model = view.recommendProduct else { return }
        
        if model.isDataBundleInfo {
            viewModel.ds_didTapDataBundleInfo(id: "\(model.id)")
            STSRouter.openURLString(model.link)
            return
        }
        scrollToTop()
        utmString = ""
        productDetailRequest(product: model)
        viewModel.ds_didTapRecommend(product: model)
    }
}

// MARK: - 代理事件 MBCommodityDetailCellDelegate
extension STMobileCommodityController: MBCommodityDetailCellDelegate {
    
    func commodityDetailCell(_ view: MBCommodityDetailCell, didSelectItemAt index: Int) {
        guard let model = view.viewModel?.commoditys[index] else { return }
        viewModel.selectedCommodity = model
        collectionView.reloadData()
        reloadBuyNowInfo()
//        buyNowView.needShowCoupon = !viewModel.isFromCoupons
//        buyNowView.model = model
//        buyNowView.productModel = viewModel.currentProduct
//        buyNowView.currentChannel = viewModel.channelsSection?.commodityChannel?.selectedChannel
        reloadBuyNowInfo()
        viewModel.ds_didTapCommodity(commodity: model)
    }
}

// MARK: - 代理事件 MBCommodityEffectiveCellDelegate
extension STMobileCommodityController: MBCommodityEffectiveCellDelegate {
    
    func commodityEffectiveCellDidSelected(_ view: MBCommodityEffectiveCell) {
        let model = view.model
        viewModel.selectedCommodity = model
        collectionView.reloadData()
        reloadBuyNowInfo()
//        buyNowView.needShowCoupon = !viewModel.isFromCoupons
//        buyNowView.model = model
//        buyNowView.productModel = viewModel.currentProduct
//        buyNowView.currentChannel = viewModel.channelsSection?.commodityChannel?.selectedChannel
        guard let commodity = model else { return }
        viewModel.ds_didTapCommodity(commodity: commodity)
    }
}

// MARK: - 代理事件 BuyNowFloatingViewDelegate
extension STMobileCommodityController: BuyNowFloatingViewDelegate {
    
    func buyNowFloatingViewDidTapBuyNow(_ view: BuyNowFloatingView) {
        didTapBuyPay()
    }
}

// MARK: - 代理事件 MBChannelCellDelegate
extension STMobileCommodityController: STChannelCellDelegate {
    
    func channelCellDidTapSelected(_ view: STChannelCell) {
        viewModel.channelsSection?.commodityChannel?.selectedChannel = view.model
        collectionView.reloadData()
        reloadBuyNowInfo()
//        buyNowView.needShowCoupon = !viewModel.isFromCoupons
//        buyNowView.currentChannel = viewModel.channelsSection?.commodityChannel?.selectedChannel
    }
    
    func channelCellDidTapDiscount(_ view: STChannelCell) {
        guard let channel = view.model else { return }
        if channel.promotionDesc.isEmpty { return }
        
        let alertView = MBDiscountAlertView()
        alertView.textView.text = channel.promotionDesc
        alertView.show(in: self.view)
    }
}

// MARK: - 代理事件 MBChannelCardCellDelegate
extension STMobileCommodityController: STChannelCardCellDelegate {
    
    func channelCardCellDidTapSelected(_ view: STChannelCardCell) {
        viewModel.channelsSection?.commodityChannel?.selectedChannel = view.model
        collectionView.reloadData()
        reloadBuyNowInfo()
//        buyNowView.needShowCoupon = !viewModel.isFromCoupons
//        buyNowView.currentChannel = viewModel.channelsSection?.commodityChannel?.selectedChannel
    }
    
    func channelCardCellDidTapAddCard(_ view: STChannelCardCell) {
        if !STUserModel.shared.isRealUser() {
            STAlertHelper.manager.show(message: "alert_login".localized(), title: "notice_".localized(), defalutButton: "confirm_".localized(), cancelButton: "cancel_".localized(), isCancel: true, inView: self.view.superview, defaultAction:  {
                STSRouter.openLocalPage(RouterPage.login)
            })
            return
        }
        
        guard let commodity = viewModel.selectedCommodity,
              let channel = view.model else { return }
        gotoBuyPay(commodity: commodity, channel: channel)
    }
}

// MARK: - 代理事件 MBChannelFooterViewDelegate
extension STMobileCommodityController: STChannelFooterViewDelegate {
    
    func channelFooterView(_ view: STChannelFooterView, didTapControl button: UIButton) {
        guard let sectionIndex = view.mobileViewModel?.sectionIndex else { return }
       
        collectionView.reloadData()
        if button.isSelected { return }
        guard collectionView.numberOfSections > sectionIndex else {
            return
        }
        collectionView.scrollToItem(at: IndexPath(row: 0, section: sectionIndex), at: .centeredVertically, animated: true)
    }
}

extension STMobileCommodityController: MBCouponAlertDelegate {
    
    func couponAlertDidTapWillClose(view: MBCouponAlert) {
        guard let commodity = view.model else { return }
        buyNowView.actualPriceLabel.text = String(commodity.startPrice)
    }

    func couponAlertDidTapClose(view: MBCouponAlert) {
        couponAlertView?.removeFromSuperview()
        guard let commodity = view.model else { return }
        
        let price = commodity.startPrice
        let finalPrice = commodity.endPrice
        buyNowView.startAnimationPrice(price, to: finalPrice)
        couponAlertView = nil
    }
}
